<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

const loginForm = ref({
  username: '1003',
  password: '1003',
  role: 'organizer'
})

const handleLogin = async () => {
  try {
    console.log('登录信息:', loginForm.value)

    let url = ''
    switch(loginForm.value.role) {
      case 'admin':
        url = 'http://localhost:8080/manager/login'
        break
      case 'organizer':
        url = 'http://localhost:8080/organizer/login'
        break
      case 'user':
        url = 'http://localhost:8080/api/user/login'
        break
      default:
        url = 'http://localhost:8080/login'
    }

    const params = new URLSearchParams()
    params.append('account', loginForm.value.username)
    params.append('password', loginForm.value.password)

    const response = await axios.post(url, params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })

    console.log('登录响应:', response.data)

    if (response.data.success) {
       // 🎯 添加这行调试代码：
  console.log('登录响应完整数据:', JSON.stringify(response.data, null, 2))
      // 保存完整的登录信息（新增内容）
      localStorage.setItem('token', response.data.token || '')
      // 存储用户账号和角色信息
      localStorage.setItem('userInfo', JSON.stringify({
        username: loginForm.value.username,
        role: loginForm.value.role
      }))
     // 🎯 修复这里：从 user 对象中获取用户ID
// 🎯 修复这里：使用正确的字段名 userID（大写D）
  if (response.data.user && response.data.user.userID) {
    localStorage.setItem('userId', response.data.user.userID.toString())
    console.log('保存的用户ID:', response.data.user.userID)
  }

  console.log('登录成功，返回数据:', response.data)

      // 存储用户ID（如果后端返回）
      if (response.data.userId) {
        localStorage.setItem('userId', response.data.userId)
      }

      switch(loginForm.value.role) {
        case 'admin':
          router.push('/MAmenu')
          break
        case 'organizer':
          router.push('/ORmenu')
          break
        case 'user':
          router.push('/user-center')
          break
        default:
          router.push('/Login')
      }

      alert(`欢迎, ${loginForm.value.username}! 登录成功`)
    } else {
      alert(response.data.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    // 更详细的错误提示（新增内容）
    const errorMsg = error instanceof Error ? error.message : '未知错误'
    alert(`登录失败: ${errorMsg}`)
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="login-title">登&nbsp;&nbsp;&nbsp;&nbsp;录</h1>
      <form @submit.prevent="handleLogin" class="login-form">
        <!-- 将角色选择移到前面 -->
        <div class="form-row">
          <label class="form-label">身&nbsp;&nbsp;&nbsp;&nbsp;份:&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <div class="radio-group">
            <label class="radio-button">
              <input
                type="radio"
                v-model="loginForm.role"
                value="admin"
              />
              <span class="radio-text">管理员</span>
            </label>

            <label class="radio-button">
              <input
                type="radio"
                v-model="loginForm.role"
                value="organizer"
              />
              <span class="radio-text">举办方</span>
            </label>

            <label class="radio-button">
              <input
                type="radio"
                v-model="loginForm.role"
                value="user"
              />
              <span class="radio-text">用户</span>
            </label>
          </div>
        </div>

        <div class="form-row">
          <label for="username" class="form-label">账&nbsp;&nbsp;&nbsp;&nbsp;号:&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <input
            id="username"
            v-model="loginForm.username"
            type="text"
            placeholder="请输入账号"
            required
            class="form-input"
          />
        </div>

        <div class="form-row">
          <label for="password" class="form-label">密&nbsp;&nbsp;&nbsp;&nbsp;码:&nbsp;&nbsp;&nbsp;&nbsp;</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
            class="form-input"
          />
        </div>

        <button type="submit" class="login-button">登录</button>
      </form>

      <div class="login-footer">

        <router-link to="/Register" class="register-link">注册新用户</router-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  width: 100%;
  min-height: 100%;
  padding-top: 2vh; /* 上部留白大约占页面高度的20% */
}

.login-box {
  width: 100%;
  max-width: 450px;
  padding: 2.5rem;
  background: rgba(255, 255, 255, 0.85); /* 半透明白色背景让背景的绿植能透出来 */
  border: 1px solid #A5D6A7; /* 浅草绿色细边框 */
  border-radius: 12px; /* 加大圆角 */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15), inset 0 0 10px rgba(129, 199, 132, 0.2); /* 添加绿色内阴影模拟透光感 */
  margin: 1rem auto;
}

.login-title {
  text-align: center;
  margin-bottom: 2rem;
  background: linear-gradient(to right, #2E7D32, #81C784); /* 深绿到浅绿的自然系渐变 */
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  font-size: 1.8rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
  text-shadow: 0 0 5px rgba(129, 199, 132, 0.5); /* 轻微发光效果 */
}

.login-form {
  display: flex;
  flex-direction: column;
  padding-left: 25px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  justify-content: flex-start;
}

.form-label {
  width: 80px;
  text-align: right;
  margin-right: 0.5rem;
  color: #555;
  font-weight: bold;
  font-size: 1.1rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
}

.form-input {
  flex: 1;
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  flex: 1;
  padding: 0.9rem;
  background: rgba(255, 255, 255, 0.7); /* 更透明的白色背景 */
  border: 1px solid #A5D6A7; /* 浅草绿色边框 */
  border-radius: 8px; /* 加大圆角 */
  font-size: 1.1rem;
  box-sizing: border-box;
  height: 3rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
  caret-color: #4CAF50; /* 绿色光标 */
}

.form-input:focus {
  outline: none;
  border-color: #31B310;
  box-shadow: 0 0 0 2px rgba(49, 179, 16, 0.2);
  border-color: #4CAF50; /* 深一点的绿色 */
  box-shadow: 0 0 3px rgba(76, 175, 80, 0.3); /* 轻微的绿色阴影 */
}

.radio-group {
  display: flex;
  align-items: center;
  gap: 1.2rem;
  flex: 1;
  margin-left: 0.5rem;
}

.radio-button {
  flex: 1;
}

.radio-button input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
}

.radio-text {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem;
  padding: 0.7rem;
  border: 1px solid #ddd;
  border-radius: 8px; /* 加大圆角 */
  color: #555;
  cursor: pointer;
  transition: all 0.2s;
  box-sizing: border-box;
  min-height: 3rem;
  font-size: 1.1rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
  background-color: #E0F7E0; /* 浅绿灰色未选中状态 */
}

.radio-button input:checked + .radio-text {
  background-color: #31B310;
  background-color: #4CAF50; /* 清新绿色选中状态 */
  color: white;
  border-color: #4CAF50;
}

.radio-button:hover .radio-text {
  background-color: #C8E6C9; /* hover时更亮的浅绿 */
  border-color: #4CAF50;
}

.login-button {
  background-color: #31B310;
  color: white;
  background: linear-gradient(to bottom, #66BB6A, #43A047); /* 浅绿到深绿的渐变 */
  color: #FFF;
  border: none;
  border-radius: 8px; /* 加大圆角 */
  font-size: 1.2rem;
  cursor: pointer;
  margin-top: 1.5rem;
  font-weight: bold;
  width: 100%;
  height: 3.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
}

.login-button:hover {
  background-color: #2a990e;
  background: linear-gradient(to bottom, #388E3C, #2E7D32); /* hover时渐变加深 */
}

.login-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 1.5rem;
  padding-left: 25px;
}

.forgot-password {
  color: #558B2F; /* 深橄榄绿 */
  text-decoration: none;
  font-size: 1rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
}

.login-footer a {
  color: #31B310;
}
.forgot-password:hover {
  color: #2E7D32; /* hover时加深 */
  text-decoration: underline;
}
.register-link {
  color: #388E3C; /* 活力绿 */
  text-decoration: none;
  font-size: 1rem;
  font-family: "微软雅黑 Light", sans-serif; /* 圆润字体 */
}

.register-link:hover {
  color: #1B5E20; /* hover时加深 */
  text-decoration: underline;
}
</style>
